using System;
using QFramework;
using Sirenix.OdinInspector;
using UniRx;
using UnityEngine;
using UnityEngine.UI;


[Serializable]
public class UniRxExample_1 :MonoBehaviour
{
    public BindableProperty<int> MyIntProperty
    {
        get;
        private set;
    }
    private CompositeDisposable CompositeDisposable;
    
    private IDisposable curDisposables;
    
    private Subject<int> timerSubject = new Subject<int>();
    
    public IObservable<int> OnTimeChanged
    {
        get { return timerSubject; }
    } 
    
    private void Start()
    {
        CompositeDisposable = new CompositeDisposable();

        healthBar.value = ((float)health.Value/ MaxHealth);
    }

    [Button("触发一个Rx延时方法")]
    public void UniRxFunction()
    {
        Debug.Log("延时-开始");
        Observable.Timer(TimeSpan.FromSeconds(5))
            .Subscribe(_ => { })
            .AddTo(CompositeDisposable);
    }
    
    
    [Button("触发一个Rx循环方法")]
    public void UniRxCompositeDis()
    {
        Observable.Interval(TimeSpan.FromSeconds(1))
            .Subscribe(x => Debug.Log(x))
            .AddTo(CompositeDisposable);
    }

    [Button("销毁所有的流程对象")]
    public void CheckAndDisposeBag()
    {
        if (curDisposables != null)
        {
            CompositeDisposable.Dispose();
        }

        foreach (var value in CompositeDisposable)
        {
            value.Dispose();
        }
    }
    
    public ReactiveProperty<int> health = new ReactiveProperty<int>(100);
    public int MaxHealth = 100;
    public Slider healthBar;
    
    [Button("监听Hp变化")]
    public void ListenHpChange()
    {
        // 监听字段变化并更新 UI
        this.ObserveEveryValueChanged(_ => health)
            .DistinctUntilChanged()
            .Subscribe(v => healthBar.value = ((float)v.Value/MaxHealth))
            .AddTo(this);
    }

    [Button("修改Hp")]
    public void HpChangeEvent()
    {
        health.Value = 20;
        // 如果能编译通过，说明安装了 Rx
        var observable = Observable.Return("Hello Rx");
        Console.WriteLine("Rx is available!");
    }
    
    public void Test22()
    {
        // 代码做的事情有：
        // 1.开启监听Undate
        // 2.在每次Undate里监听是鼠标是否按下  
        // 3.判断是否是第一次点击  
        // 4.订阅/处理事件
        
        //具有Mono全部生命周期
        Observable.EveryUpdate()
            .Where(_ => Input.GetMouseButtonUp(0))
            .First()
            .Subscribe(_ => { });
        
        // 定时器功能
        Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(_ => { });
        
        Observable.EveryUpdate()
            .Subscribe(_ =>
            {
                if (Input.GetMouseButtonUp(0))
                {
                    // do something
                }
            }).AddTo(this);
    }

    /// <summary>
    /// 
    /// </summary>
    [Button]
    public void EveryUpateTest()
    {
        Observable.EveryUpdate()
            .Do(_ => Debug.Log(Time.frameCount));
        // .First()
        // .Subscribe(_ => { Debug.Log("点击鼠标"); });
    }
}